package bdqn;

import java.sql.*;
import java.util.*;

/*
 * 实现类
 */
public class ImplClass extends RefTest implements GradeDAO, StudentDAO,ExamResultDAO{
	// 显示年级
	public void showGrade() {
		String sql = "select * from grade order by id";
		List<Grade> datas = super.query2(sql, Grade.class);

		for (int i = 0; i < datas.size(); i++) {
			System.out.print(datas.get(i).getId() + ":"
					+ datas.get(i).getGname());
			if (i != datas.size() - 1) {
				System.out.print(",");
			}
		}
		System.out.println();
	}

	// 根据年级编号获得相应课程
	public boolean showSubject(int gradeid) {
		String sql = "select * from subject where gradeid in(select id from grade where id="
				+ gradeid + ")";
		List<Subject> datas = super.query2(sql, Subject.class);
		if (datas != null) {
			System.out.print("开设科目：");
			for (int i = 0; i < datas.size(); i++) {
				System.out.print(datas.get(i).getSubjectname());
				if (i != datas.size() - 1) {
					System.out.print(",");
				}
			}
			System.out.println();
			return true;
		}
		return false;
	}

	// 注册
	public long register(Student s) {
		String sql = "insert into student(sname,sex,fromcity,gradeid,qq,password) values(?,?,?,?,?,?)";
		Connection con = RefTest.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = con.prepareStatement(sql,
					PreparedStatement.RETURN_GENERATED_KEYS);
			ps.setString(1, s.getSname());
			ps.setString(2, s.getSex());
			ps.setString(3, s.getFromcity());
			ps.setInt(4, s.getGradeid());
			ps.setString(5, s.getQq());
			ps.setString(6, s.getPassword());
			ps.executeUpdate();
			long auto = 0;
			rs = ps.getGeneratedKeys();
			rs.next();
			auto = rs.getLong(1);
			return auto;
		} catch (SQLException e) {
			e.printStackTrace();
			return -1;
		} finally {
			super.close(con, ps, rs);
		}
	}

	// 登录
	public boolean login(long stuno, String password) {
		String sql = "select stuno from student where stuno=? and password=?";
		Object[] args = { stuno, password };
		List<Student> datas = super.query2(sql, Student.class, args);
		if (datas.size() != 0) {
			return true;
		}
		return false;
	}

	// 录入考试成绩
	public boolean addScore(ExamResult e) {
		String sql = "insert into examresult(exam_date,score,st_id,sb_id)values(?,?,?,?)";
		Object[] args = { e.getExam_date(), e.getScore(), e.getSt_id(),
				e.getSb_id() };
		int num = super.executeUpdate(sql, args);
		if (num == -1 || num == 0) {
			return false;
		}
		return true;
	}
}
